import pymysql
from utils import logging_method
from entity import mysql_config
import datetime


class MysqlConnector:
    def __init__(self, table_name,
                 host=mysql_config.host(),
                 port=mysql_config.port(),
                 user=mysql_config.user(),
                 password=mysql_config.password(),
                 database=mysql_config.database(),
                 charset=mysql_config.charset()):
        self.table_name = table_name
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    def open(self):
        self.db = pymysql.connect(host=self.host, user=self.user, password=self.password, port=self.port,
                                  database=self.database, charset=self.charset)
        self.cur = self.db.cursor()

    def close(self):
        self.db.close()
        self.cur.close()

    def operation(self, sql):
        self.open()
        try:
            self.cur.execute(sql)
            # cursor.execute("select * from biao where name = ?;", ["aa", ])
            self.db.commit()
            return self.cur.fetchall()
        except Exception as e:
            self.db.rollback()
            logging_method.error(e)
        self.close()
        return None

    def insert(self, result_dict):
        keys = ''
        values = ''
        for key in result_dict.keys():
            if key is None:
                # logging_method.warning('访问链接：', result_dict['url'], '；为None的字段值是：', result_dict[key])
                continue
            elif key == '':
                continue
            try:
                keys = keys + key + ','
                values = (values + '"{}"' + ',').format(result_dict[key])
            except Exception as e:
                logging_method.error(e)
                continue
        sql = "INSERT INTO %s (%s) VALUES (%s)" % (self.table_name, keys[:-1], values[:-1])
        print(datetime.datetime.now(), sql)
        return sql

    def update(self, result_dict, condition):
        sets = []
        for key in result_dict.keys():
            if key is None:
                # logging_method.warning('访问链接：', result_dict['url'], '；为None的字段值是：', result_dict[key])
                continue
            elif key == '':
                continue
            try:
                set_val = "%s='%s'" % (key, result_dict[key])
                sets.append(set_val)
            except Exception as e:
                logging_method.error(e)
                continue
        values = ",".join(sets)
        sql = "UPDATE %s SET %s %s" % (self.table_name, values, condition)
        print(datetime.datetime.now(), sql)
        return sql
